% This code aggregates cost estimates to the market level and exports them 
% for regressions to be performed in cost_estimates_regression.do in Stata.
function export_cost_estimates(cost2_0_mat, cost2_1, cost1_e, N_st, D_unmerge, D)
%% bring down rate stability regulation estimates to market level
cost2_0_vec = cost2_0_mat(:,1);
cost2_0_mkt = zeros(N_st,1);
for mm=1:N_st
    cost2_0_mkt(mm) = unique(cost2_0_vec(D_unmerge.mkt==mm));
end

% integrate over aggregate states
Ecost2_1= sum(D_unmerge.pr_s.*cost2_1,2); % NN x 1

% for each market, integrate over firms
Ecost2_1_mkt_sw = zeros(N_st,1); % use market shares as the weight
Ecost2_1_mkt_ew = zeros(N_st,1); 

for mm=1:N_st
    % use market shares as the weight
    temp = Ecost2_1(D_unmerge.mkt==mm);
    s1_mm = D_unmerge.s1(D_unmerge.mkt==mm);
    Ecost2_1_mkt_sw(mm) = sum(temp.*s1_mm);

    % assign equal weight 
    temp_m = Ecost2_1(D_unmerge.mkt==mm & D_unmerge.major==1);
    temp_f = Ecost2_1(D_unmerge.mkt==mm & D_unmerge.major==0);
    temp_f = temp_f(1); 
    temp = [temp_m; temp_f];
    Ecost2_1_mkt_ew(mm) = mean(temp);
end

% compute market-level averages of cost1_e (initial rate
% regulatory cost)
cost1_e_mkt_sw = zeros(N_st,1); % use market shares as the weight
cost1_e_mkt_ew = zeros(N_st,1); 

for mm=1:N_st
    % use market shares as the weight
    temp = cost1_e(D_unmerge.mkt==mm);
    s1_mm = D_unmerge.s1(D_unmerge.mkt==mm);
    cost1_e_mkt_sw(mm) = sum(temp.*s1_mm);

    % assign equal weight
    temp_m = cost1_e(D_unmerge.mkt==mm & D_unmerge.major==1);
    temp_f = cost1_e(D_unmerge.mkt==mm & D_unmerge.major==0);
    temp_f = temp_f(1); 
    temp = [temp_m; temp_f];
    cost1_e_mkt_ew(mm) = mean(temp);
end

%% export mkt-level data for regressions to be performed in Stata
state_mkt    = zeros(N_st,1);
year_mkt     = zeros(N_st,1);
reg_year_mkt = zeros(N_st,1);
in_regression_mkt = zeros(N_st,1);

for mm=1:N_st
    state_mkt(mm)=unique(D.state(D.mkt==mm));
    year_mkt(mm)=unique(D.year(D.mkt==mm));
    in_regression_mkt(mm) = unique(D.in_regression(D.mkt==mm));

    temp = D.reg_year(D.mkt==mm);
    if sum(isnan(temp))==0 % reg year non-missing, i.e., implemented in some year
        reg_year_mkt(mm)=unique(temp);
    else
        reg_year_mkt(mm)=3000; % if reg year missing
    end
end

% export
X_stata = [cost2_0_mkt Ecost2_1_mkt_sw Ecost2_1_mkt_ew state_mkt year_mkt reg_year_mkt in_regression_mkt cost1_e_mkt_sw cost1_e_mkt_ew];
csvwrite('cost_estimates_market_level.csv', X_stata);

